package designpattern.template.jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class JdbcTemplate extends MyDataSource{

    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;

    //查询
    protected <T> List<T> executeQuery(String sql , RowMapper<T> rowMapper) throws SQLException {
        if (sql == null || sql.equals("")) throw new SQLException("sql is null");
        preparedStatement = preparedStatement(sql);
        resultSet = preparedStatement.executeQuery();
        List<T> list = resultSet(resultSet, rowMapper);
        close();
        return list;
    }

    //更新
    protected int executeUpdate(String sql) throws SQLException {
        if (sql == null || sql.equals("")) throw new SQLException("sql is null");
        preparedStatement = preparedStatement(sql);
        int i = preparedStatement.executeUpdate();
        close();
        return i;
    }

    //获取链接
    private Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    //预执行sql
    private PreparedStatement preparedStatement(String sql) throws SQLException {
        this.connection = getConnection();
        return connection.prepareStatement(sql);
    }

    //结果集
    private <T> List<T> resultSet(ResultSet resultSet , RowMapper<T> rowMapper) throws SQLException {
        List<T> list = new ArrayList<>();
        while (resultSet.next()){
            list.add(rowMapper.mapRow(resultSet));
        }
        return list;
    }

    //关闭
    private void close() throws SQLException {
        if (this.connection != null) this.connection.close();
        if (this.preparedStatement != null) this.preparedStatement.close();
        if (this.resultSet != null) this.resultSet.close();
    }
}
